package fr.xebia.monitoring.config;

import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

public class MonitoringConfigLoader {
	
	private static final String DEFAULT_MONITORING_XML = "monitoring.xml";

	private static final Logger logger = Logger.getLogger(MonitoringConfigLoader.class);

	public MonitoringConfig configure() {
		return configure(null);
	}

	public MonitoringConfig configure(String configFilename) {
		if (configFilename == null) {
			configFilename = DEFAULT_MONITORING_XML;
		}
		InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFilename);
		if (configStream == null) {
			logger.info("No monitoring configuration file found in classpath. Monitoring is disabled");
			return createEmptyConfig();
		}
		logger.info("Found config file in classpath: "+configFilename);
		MonitoringConfig monitoringConfig;
		try {
			JAXBContext context = JAXBContext.newInstance(MonitoringConfig.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			monitoringConfig = (MonitoringConfig) unmarshaller.unmarshal(configStream);
			logger.info("Successfully read config file: "+configFilename);
		} catch (JAXBException e) {
			monitoringConfig = createEmptyConfig();
			logger.error("Error reading monitoring config file ("+configFilename+"). Monitoring is disabled", e);
		}
		if (monitoringConfig.getRoot().isEnable()) {
			logger.info("Monitoring is enabled");
		} else {
			logger.info("Monitoring is disabled");
		}
		return monitoringConfig;
	}

	private MonitoringConfig createEmptyConfig() {
		MonitoringConfig monitoringConfig = new MonitoringConfig();
		monitoringConfig.setRoot(new RootConfig());
		monitoringConfig.getRoot().setEnable(false);
		return monitoringConfig;
	}
}
